const app = getApp();
const util = require('../../utils/util.js');
let flag = 1;
Page({
  data: {
    userInfo: {},
    info: {},
    isClick: true,
    checkNum: 0,
    used_id: "",
    need_tel: 0,
    refuse_show: 0,
    refuse_msg: "",
    refuse_after_borrow: 1,
    need_tel_tip_1: "授权手机号",
    need_tel_tip_2: "",
    timer: '',
    showTipsNeed: 0,
    showTipValue: "",
    adImg: "",
    isShow: 0
  },
  onLoad(options) {
    my.showLoading({
      content: 'loading...'
    });
    // 获取用户信息
    this.getUserInfo();
    // 将传输过来的信息保存起来
    var jsonParse = JSON.parse(options.data);
    this.setData({
      info: jsonParse,
      showTipsNeed: jsonParse.showTipsNeed,
      showTipValue: jsonParse.showTipValue,
      adImg: jsonParse.adImg,
      isShow: jsonParse.isShow,
      need_tel: jsonParse.need_tel,
      // need_tel: 1,
      refuse_show: jsonParse.refuse_show,
      refuse_msg: jsonParse.refuse_msg,
      refuse_after_borrow: jsonParse.refuse_after_borrow,
      need_tel_tip_1: jsonParse.need_tel_tip_1,
      // need_tel_tip_1: "授权手机号",
      need_tel_tip_2: jsonParse.need_tel_tip_2,
    });
    my.hideLoading();
  },
  // 页面隐藏/切入后台时触发。 如 my.navigateTo 到其他页面或底部 tab 切换等
  onHide() {
    this.setData({
      isClick: true
    });
    clearInterval(this.data.timer);
  },
  // 页面卸载时触发。 如 my.redirectTo 或 my.navigateBack 到其他页面等。
  onUnload() {
    this.setData({
      isClick: true
    });
    clearInterval(this.data.timer);
  },
  // =============== 获取用户信息 ====================
  getUserInfo() {
    let that = this;
    util.httpRequest('/getInfo', {}, function (res) {
      if (res.code == 1) {
        that.setData({
          userInfo: res.data.user
        })
      }
    })
  },
  onShow() {
    this.setData({
      isClick: true
    });
    flag = this.data.info.freeDeposit;
    if (flag == 1) {
      flag = 1;
    } else {
      flag = 0;
    }
  },

  // ====================== 实际：押金租借
  startDepositFeignBorrow() {
    let that = this;
    // 展示弹框
    my.confirm({
      title: '温馨提示',
      content: that.data.showTipValue, // 提示文字
      confirmButtonText: '押金租借',
      cancelButtonText: '关闭',
      success: (result) => {
        if (result.confirm) {
          // 用户点击了确认，进行押金租借
          that.startBorrow();
        } else {
          my.alert({
            title: '您点击了取消',
          });
          that.setData({
            isClick: true
          });
        }
      },
    });
  },
  // ====================== 开始押金租借  ===========================================
  startBorrow() {
    let that = this;
    if (that.data.isClick) {
      my.showLoading({
        content: '请稍后...'
      });
      that.setData({
        isClick: false
      });
      util.httpRequest('/deviceBorrow', {
        sn: that.data.info.sn,
        freeDeposit: 0
      }, function (res) {
        switch (res.code) {
          case 1://开始租借
            my.hideLoading();
            my.navigateTo({
              url: '../onLoan/onLoan?data=' + JSON.stringify(res.data)
            });
            break;
          case 3://余额不足
            my.showLoading({
              content: '请稍后...'
            });
            util.alipayPayment(res.data.amount, 1, res.data.sn, 0, function (order_id) {
              my.hideLoading();
              if (order_id != null) {
                that.checkOrderStatus(order_id);
              } else {
                that.setData({
                  isClick: false
                });
              }
            }, function () {
              that.setData({
                isClick: true
              });
              my.hideLoading();
            });
            break;
          case 4: // 存在未支付的金额
            my.hideLoading();
            my.confirm({
              title: '温馨提示',
              content: res.msg, // 提示文字
              confirmButtonText: '马上查看',
              cancelButtonText: '关闭',
              success: (result) => {
                if (result.confirm) {
                  // 用户点击了确认，跳转到要支付的页面, 押金补足支付
                  my.navigateTo({
                    url: '../payMoney/payMoney?used_id=' + res.data.used_id + "&free_deposit=0"
                  });
                } else {
                  my.alert({
                    title: '您点击了取消',
                  });
                  that.setData({
                    isClick: true
                  });
                }
              },
            });
            break;
          default:
            that.setData({
              isClick: true
            });
            my.hideLoading();
            break;
        }
      }, function () {
        that.setData({
          isClick: true
        });
        my.hideLoading();
      })

    }
  },
  // ====================== 校验用户是否支付成功  ===========================================
  checkOrderStatus(order_id) {
    let that = this;
    let check = that.data.checkNum;
    check++;
    that.setData({
      checkNum: check
    });
    my.showLoading({
      content: '请稍后...'
    });
    if (that.data.checkNum < 20) {
      util.httpRequest('/checkOrderStatus', {
        order_id: order_id,
        freeDeposit: flag
      }, function (res) {
        my.hideLoading();
        if (res.data.status == 1) {
          clearInterval(that.data.timer);
          if (that.data.info.freeDeposit == 1) {
            that.setData({
              isClick: true,
              used_id: res.data.used_id
            });
            that.startFreeBorrow();
          } else {
            that.setData({
              isClick: true
            });
            that.startBorrow();
          }
        } else {
          var timerTem = setTimeout(() => {
            that.checkOrderStatus(order_id);
          }, 1500);
          that.setData({
            timer: timerTem
          });
        }
      }, function () {
        my.hideLoading();
      })
    } else {
      my.showToast({
        content: '订单异常,请联系客服',
        duration: 2000
      });
      my.hideLoading();
    }
  },
  // ==========================  芝麻信用租借 ============================
  startFreeBorrow() {
    let that = this;
    if (that.data.isClick) {
      my.showLoading({
        content: '请稍后...'
      });
      that.setData({
        isClick: false
      });
      let used_id = that.data.used_id;
      util.httpRequest('/deviceBorrow', {
        sn: that.data.info.sn,
        freeDeposit: 1,
        used_id: used_id
      }, function (res) {
        switch (res.code) {
          case 1:
            //开始租借
            my.hideLoading();
            my.navigateTo({
              url: '../onLoan/onLoan?data=' + JSON.stringify(res.data)
            });
            break;
          case 3:
            // 发起预授权
            my.showLoading({
              content: '请稍后...'
            });
            util.alipayFreeze(res.data.amount, res.data.sn, function (used_id) {
              my.hideLoading();
              if (used_id != null) {
                that.setData({
                  isClick: true,
                  used_id: used_id
                });
                that.checkOrderStatus(used_id);
              } else {
                that.setData({
                  isClick: true
                });
              }
            }, function () {
              that.setData({
                isClick: true
              });
              my.hideLoading();
            });
            break;
          case 4:
            //开始租借
            that.setData({
              isClick: false,
              used_id: res.data.used_id
            });
            my.hideLoading();
            my.showToast({
              content: res.data.msg,
              type: 'none',
              duration: 3000
            });
            break;
          case 3:
          default:
            that.setData({
              isClick: true
            })
            my.hideLoading();
            break;
        }
      }, function () {
        that.setData({
          isClick: true
        });
        my.hideLoading();
      })

    }
  },

  // ==========================  发送formId至后台 ============================
  formGoTo(e) {
    let formId = e.detail.formId;
    // util.httpRequest('/saveAlipayFormId', {
    //     formId: formId,
    // }, function (res) {
    //     if (res.code == 1) {
    //         console.log(res.data)
    //     }
    // })
  },

  // ========================== 手机号授权start ============================

  // 用户取消授权
  onAuthError() {
    let that = this;
    // 用户拒绝
    let refuseShow = that.data.refuse_show;
    let refuseAfterToBorrow = that.data.refuse_after_borrow;
    if (refuseShow == 1) {
      my.alert({
        title: that.data.refuse_msg,
      });
    }
    if (refuseAfterToBorrow == 1 || refuseAfterToBorrow == null) {
      that.setData({
        need_tel: 0
      });
    }
  },
  // 用户确认授权
  onGetAuthorize() {
    my.getPhoneNumber({
      success: (res) => {
        let encryptedData = res.response;
        console.log(encryptedData);
        util.httpRequest('/getPhoneNumber', {
          encryptedData: encryptedData
        }, function (res) {
          if (res.code == 1) {
            my.showToast({
              content: "授权成功",
              type: 'none',
              duration: 3000
            });
          }
        })
      },
      fail: (res) => {
        console.log(res);
        // console.log('getPhoneNumber_fail');
      },
    });
    // 不管是否授权成功，只要用户点击了授权，则设置成功
    this.setData({
      need_tel: 0
    });
  }


});
